package com.tao.com.xiaowen.module.jokecomment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.tao.com.xiaowen.config.http.MyJson;
import com.tao.com.xiaowen.adapter.JokeCommentAdapter;
import com.tao.com.xiaowen.module.me.LoginActivity;
import com.tao.com.xiaowen.model.Comment;
import com.tao.com.xiaowen.model.JokeData;
import com.tao.com.xiaowen.model.Model;
import com.tao.com.xiaowen.event.UserInfoEvent;
import com.tao.com.xiaowen.model.UserInfos;
import com.tao.com.xiaowen.R;
import com.tao.com.xiaowen.config.tecent.BaseUiListener;
import com.tao.com.xiaowen.config.tecent.GetUserAuth;
import com.tencent.connect.UserInfo;
import com.tencent.tauth.Tencent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;

/**
 * Created by Administrator on 2016/8/4.
 */
public class JokeCommentActivity extends AppCompatActivity {
    private Tencent tencent;
    private UserInfo userInfo;
    private long time = 0;
    private BmobUser bmobUser;
    private String expires_in = null;

    private TextView contentView;
    private TextView idView;
    private ImageView picUrlView;
    private ImageButton btnReturn;
    private EditText editComment;
    private Button sendComment;
    private LinearLayout defaultContent;
    private TextView happyNum;

    private XRecyclerView recyclerView;
    private List<Comment> commentList;
    private JokeCommentAdapter jokeCommentAdapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_joke_comment);
//        Bmob.initialize(this, Model.APP_ID_BMOB);
        tencent = Tencent.createInstance(Model.APP_ID_QQ, this);
        EventBus.getDefault().register(this);

        initView();
        initUserInfo();
//        initComment();
        initNum();
    }

    private void initNum() {
        String j = getIntent().getStringExtra("joke");
        final String id = getIntent().getStringExtra("hashId");
        if (j.equals("joke")) {
            BmobQuery<JokeData> query = new BmobQuery<>();
            query.order("created");
            query.findObjects(new FindListener<JokeData>() {
                @Override
                public void done(List<JokeData> list, BmobException e) {
                    for (JokeData joke : list) {
                        if (id.equals(joke.getHashId())) {
                            happyNum.setText(String.valueOf(joke.getSupportNum()));
                        }
                    }
                }
            });
        } else {
            BmobQuery<JokeData> query = new BmobQuery<>();
            query.order("created");
            query.findObjects(new FindListener<JokeData>() {
                @Override
                public void done(List<JokeData> list, BmobException e) {
                    for (JokeData joke : list) {
                        if (id.equals(joke.getHashId())) {
                            happyNum.setText(String.valueOf(joke.getSupportNum()));
                        }
                    }
                }
            });
        }
    }

    private void initUserInfo() {
        userInfo = new UserInfo(this, tencent.getQQToken());
        userInfo.getUserInfo(new BaseUiListener() {
            @Override
            public void onComplete(Object o) {
                super.onComplete(o);
                initData(o);
            }
        });
    }

    private void initComment() {
        BmobQuery<Comment> query = new BmobQuery<Comment>();
        query.order("-createdAt");

        query.findObjects(new FindListener<Comment>() {
            @Override
            public void done(List<Comment> list, BmobException e) {
                if (list != null) {
                    commentList.clear();
                    for (Comment comment : list) {
                        String id = getIntent().getStringExtra("hashId");
                        String hashId = comment.getHashId();
                        if (id.equals(hashId)) {
                            commentList.add(comment);
                            recyclerView.refreshComplete();
                            defaultContent.setVisibility(View.INVISIBLE);
                            jokeCommentAdapter.notifyDataSetChanged();
                        }
                        if (commentList.isEmpty()) {
                            recyclerView.refreshComplete();
                            defaultContent.setVisibility(View.VISIBLE);
                        }
                    }
                }
            }
        });
    }

    private void initData(final Object object) {
        sendComment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bmobUser = BmobUser.getCurrentUser();

                InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(editComment.getWindowToken(), 0);
                String id = getIntent().getStringExtra("hashId");
                expires_in = GetUserAuth.getUserAyth(tencent, JokeCommentActivity.this);
                if (expires_in != null) {
                    time = System.currentTimeMillis() + Long.parseLong(expires_in) * 1000;
                } else {
                    time = 0;
                }
                final String commentContent = editComment.getText().toString();
                if (time > 0 || bmobUser != null) {
                    BmobUser user = BmobUser.getCurrentUser();
                    JokeData jokeData = (JokeData) getIntent().getSerializableExtra("jokeData");
                    final Comment comment = new Comment();
                    comment.setAuthor(user);
                    comment.setJokeId(jokeData);
                    if (!commentContent.equals("")) {
                        if (time > 0) {
                            UserInfos userInfos = MyJson.getUserInfoJson(object);
                            comment.setNickname(userInfos.getNickname());
                            comment.setFigureurl_qq_1(userInfos.getFigureurl_qq_1());
                        }
                        if (bmobUser != null && time == 0) {
                            String name = (String) BmobUser.getObjectByKey("username");
                            comment.setNickname(name);
                        }
                        comment.setCommentContent(commentContent);
                        comment.setHashId(id);
                        comment.save(new SaveListener<String>() {
                            @Override
                            public void done(String s, BmobException e) {
                                editComment.getText().clear();
                                commentList.clear();
                                initComment();
                                defaultContent.setVisibility(View.INVISIBLE);
                                jokeCommentAdapter.notifyDataSetChanged();
                            }
                        });

                    } else {
                        Toast.makeText(JokeCommentActivity.this, "评论不能为空！", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(JokeCommentActivity.this, "登陆后才能评论！", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(JokeCommentActivity.this, LoginActivity.class);
                    startActivity(intent);
                }
            }
        });
    }

    private void initView() {

        contentView = (TextView) findViewById(R.id.content);
        idView = (TextView) findViewById(R.id.joke_id);
        picUrlView = (ImageView) findViewById(R.id.picUrl);
        btnReturn = (ImageButton) findViewById(R.id.return_button);
        recyclerView = (XRecyclerView) findViewById(R.id.recyclerView);
        editComment = (EditText) findViewById(R.id.edit_commnet);
        sendComment = (Button) findViewById(R.id.send_comment);
        defaultContent = (LinearLayout) findViewById(R.id.default_content);
        happyNum = (TextView) findViewById(R.id.happy_num);

        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));

        recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                initComment();
            }

            @Override
            public void onLoadMore() {
                recyclerView.loadMoreComplete();
            }
        });

        recyclerView.setRefreshing(true);
        commentList = new ArrayList<>();
        jokeCommentAdapter = new JokeCommentAdapter(this, commentList);
        recyclerView.setAdapter(jokeCommentAdapter);

        String content = getIntent().getStringExtra("content");
        String picUrl = getIntent().getStringExtra("url");

        contentView.setText(content);
        if (picUrl != null) {
            picUrlView.setVisibility(View.VISIBLE);
            Glide.with(this).load(picUrl)
                    .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                    .placeholder(R.drawable.default_content_pic)
                    .error(R.drawable.default_content_pic)
                    .crossFade()
                    .into(picUrlView);
        } else {
            picUrlView.setVisibility(View.GONE);
        }

        btnReturn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });


    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUserInfoEvent(UserInfoEvent event) {
        initUserInfo();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
